<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Stream;
use Input;

use GuzzleHttp\Client;

class StreamController extends Controller
{
    //列表方法
    public function index(){
    	//获取数据
    	$data = Stream::orderBy('sort','desc') -> get();
    	//显示视图
    	return view('admin.stream.index',['data' => $data]);
    }

    //添加直播流
    public function add(){
    	if(Input::method() == 'POST'){
    		//将数据提交给七牛（创建出新的流）
    		$data = Input::all();	//获取全部数据
    		//1、生成七牛token值（鉴权）
    		$method 		= 	'POST';
    		$path			=	'/v2/hubs/education-zet/streams';
    		$host			=	'pili.qiniuapi.com';
    		$contentType 	=	'application/json';
    		$body			=	json_encode(['key' => $data['stream_name']]);
    		//2、计算 HMAC-SHA1 签名，并对签名结果做 URL 安全的 Base64 编码
    		$qiniu = new \Qiniu\Auth(config('filesystems.disks.qiniu.access_key'),config('filesystems.disks.qiniu.secret_key'));
    		$token = $qiniu -> sign("$method $path\nHost: $host\nContent-Type: $contentType\n\n$body");
    		$token = "Qiniu $token";//记住 不要删除该有的空格
    		//dd($token);
    		//将数据写入到数据表
    		//1、实例化guzzle类
    		$client = new Client([
			    //base_uri在请求的时候使用的是相对请求
			    'base_uri' => 'http://pili.qiniuapi.com'	//不要忘记协议
			]);
    		//2、发送一个post请求
    		$response = $client -> post($path,[
    				'headers'	=>	[
    						'Authorization'	=>	$token,
    						'Content-Type'	=>	$contentType
    				],
    				'body'		=>	$body
    			]);
    		//3、接收响应，判断结果
    		if($response -> getStatusCode() == '200'){
    			//dd('chenggong');
    			//数据入库
    			$result = Stream::insert([
    					'stream_name'	=>	$data['stream_name'],
    					'sort'			=>	$data['sort']
    				]);

    			return $result ? '1' : '0';
    		}
    	}else{
    		return view('admin.stream.add');
    	}
    }
}
